package com.cndongtai.controller.user;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cndongtai.constant.UserConstant;
import com.cndongtai.controller.BaseController;
import com.cndongtai.po.Role;
import com.cndongtai.po.RoleMenu;
import com.cndongtai.po.User;
import com.cndongtai.po.UserRole;
import com.cndongtai.service.user.UserService;
import com.cndongtai.util.MD5;
import com.cndongtai.util.ValidateUtil;
import com.cndongtai.vo.RoleBean;
import com.cndongtai.vo.UserBean;

@Controller
public class UserController extends BaseController {
	
	@Resource(name="userService")
	private UserService userService;
	
	@RequestMapping("/showUserList")
	public String showUserList() {
		List<UserBean> userList = userService.queryUserBeanList();
		request.setAttribute("userList", userList);
		
		List<RoleBean> roleBeanList = userService.queryRoleBeanList();
		request.setAttribute("roleList", roleBeanList);
		
		return "/system/userList";
	}
	
	@RequestMapping("/gotoAddUser")
	public String gotoAddUser() {
		List<RoleBean> roleBeanList = userService.queryRoleBeanList();
		request.setAttribute("roleList", roleBeanList);
		return "/system/addUser";
	}
	@RequestMapping("/queryUserInfo")
	@ResponseBody
	public void queryUserInfo() {
		JSONObject result = new JSONObject();
		
		String userId = this.getValue("userId");
		if(ValidateUtil.empty(userId)) {
			result.put("success", 1);
			result.put("msg","上送数据不合法");
			this.writeData(result);
			return;
		}
		
		// 获取用户信息
		User user = userService.getUserInfoById(Long.valueOf(userId));
		if(user==null) {
			result.put("success", 1);
			result.put("msg","上送数据不合法");
			this.writeData(result);
			return;
		}
		result.put("user", user);
		// 获取角色信息
		List<UserRole> roleBeanList = userService.queryUserRoleList(user.getUserId());
		result.put("roleBeanList", roleBeanList);
		result.put("success", 0);
		
		this.writeData(result);
	}
	
	
	@RequestMapping("/delUserInfo")
	@ResponseBody
	public void delUserInfo() {
		JSONObject result = new JSONObject();
		
		User loginUser = (User) request.getSession().getAttribute(UserConstant.SESSION_USER);
		if(!"admin".equals(loginUser.getUsername())) {
			result.put("success", 1);
			result.put("msg","权限不够");
			this.writeData(result);
			return;
		}
		
		String userId = this.getValue("userId");
		if(ValidateUtil.empty(userId)) {
			result.put("success", 1);
			result.put("msg","上送数据不合法");
			this.writeData(result);
			return;
		}
		
		// 获取用户信息
		User user = userService.getUserInfoById(Long.valueOf(userId));
		if(user==null) {
			result.put("success", 1);
			result.put("msg","上送数据不合法");
			this.writeData(result);
			return;
		}
		
		if("admin".equals(user.getUsername())) {
			result.put("success", 1);
			result.put("msg","最高管理员不能被删除");
			this.writeData(result);
			return;
		}
		
		// 删除数据
		if(userService.deleteUser(user)) {
			result.put("success", 0);
			result.put("msg","删除成功");
		}else {
			result.put("success", 1);
			result.put("msg","删除失败");
		}
		
		this.writeData(result);
	}
	
	@RequestMapping("/addUser")
	@ResponseBody
	public void addUser() {
		JSONObject result = new JSONObject();
		
		String username = this.getValue("username");
		String realName = this.getValue("realName");
		String company = this.getValue("company");
		String mobile = this.getValue("mobile");
		String email = this.getValue("email");
		String address = this.getValue("address");
		String remark = this.getValue("remark");
		String fatherId = this.getValue("fatherId");
		String password = this.getValue("password");
		String role = this.getValue("role");
		
		if(ValidateUtil.empty(username)) {
			result.put("success", 1);
			result.put("msg", "用户名不能为空！");
			this.writeData(result);
			return;
		}
		
		if(ValidateUtil.empty(mobile)) {
			result.put("success", 1);
			result.put("msg", "手机号不能为空！");
			this.writeData(result);
			return;
		}
		
		if(ValidateUtil.empty(password)) {
			result.put("success", 1);
			result.put("msg", "密码不能为空！");
			this.writeData(result);
			return;
		}
		
		if(ValidateUtil.empty(role)) {
			result.put("success", 1);
			result.put("msg", "请选择用户角色！");
			this.writeData(result);
			return;
		}
		
		String[] roles = role.split(",");
		if(roles.length==0) {
			result.put("success", 1);
			result.put("msg", "请选择用户角色！");
			this.writeData(result);
			return;
		}
		
		User user = new User();
		user.setUsername(username);
		user.setRealName(realName);
		user.setCompany(company);
		user.setMobile(mobile);
		user.setEmail(email);
		user.setAddress(address);
		user.setRemark(remark);
		
		if(ValidateUtil.empty(fatherId)) {
			user.setFatherId(0L);
		}else {
			user.setFatherId(Long.valueOf(fatherId));
		}
		
		String pwdStr = new MD5().getMD5ofStr(password);
		user.setPassword(pwdStr);
		User loginUser = (User) request.getSession().getAttribute(UserConstant.SESSION_USER);
		user.setCreateBy(loginUser.getUserId());
		
		String[] res = userService.insertUser(user);
		
		if(roles!=null && roles.length>0) {
			List<UserRole> userRoleList = new ArrayList<UserRole>();
			// 添加角色
			for(String roleId : roles) {
				UserRole userRole = new UserRole();
				userRole.setUserId(user.getUserId());
				userRole.setRoleId(Long.valueOf(roleId));
				userRole.setCreateBy(loginUser.getUserId());
				userRoleList.add(userRole);
			}
			
			userService.addUserRole(userRoleList);
		}
		
		if(SUCCESS.equals(res[0])) {
			result.put("success", 0);
			result.put("msg", "用户添加成功！");
			this.writeData(result);
			return;
		}else {
			result.put("success", 1);
			result.put("msg", res[1]);
			this.writeData(result);
			return;
		}
		
	}
	
	
	@RequestMapping("/updateUser")
	@ResponseBody
	public void updateUser() {
		JSONObject result = new JSONObject();
		
		String userId = this.getValue("userId");
		String username = this.getValue("username");
		String realName = this.getValue("realName");
		String company = this.getValue("company");
		String mobile = this.getValue("mobile");
		String email = this.getValue("email");
		String address = this.getValue("address");
		String remark = this.getValue("remark");
		String fatherId = this.getValue("fatherId");
		String password = this.getValue("password");
		String role = this.getValue("role");
		
		if(ValidateUtil.empty(userId)) {
			result.put("success", 1);
			result.put("msg", "数据异常！");
			this.writeData(result);
			return;
		}
		
		if(ValidateUtil.empty(username)) {
			result.put("success", 1);
			result.put("msg", "用户名不能为空！");
			this.writeData(result);
			return;
		}
		
		if(ValidateUtil.empty(mobile)) {
			result.put("success", 1);
			result.put("msg", "手机号不能为空！");
			this.writeData(result);
			return;
		}
		
		if(ValidateUtil.empty(password)) {
			result.put("success", 1);
			result.put("msg", "密码不能为空！");
			this.writeData(result);
			return;
		}
		
		if(ValidateUtil.empty(role)) {
			result.put("success", 1);
			result.put("msg", "请选择用户角色！");
			this.writeData(result);
			return;
		}
		
		String[] roles = role.split(",");
		if(roles.length==0) {
			result.put("success", 1);
			result.put("msg", "请选择用户角色！");
			this.writeData(result);
			return;
		}
		
		User user = userService.getUserInfoById(Long.valueOf(userId));
		user.setUserId(Long.valueOf(userId));
		user.setUsername(username);
		user.setRealName(realName);
		user.setCompany(company);
		user.setMobile(mobile);
		user.setEmail(email);
		user.setAddress(address);
		user.setRemark(remark);
		
		if(ValidateUtil.empty(fatherId)) {
			user.setFatherId(0L);
		}else {
			user.setFatherId(Long.valueOf(fatherId));
		}
		
		if(!"******".equals(password)) {
			String pwdStr = new MD5().getMD5ofStr(password);
			user.setPassword(pwdStr);
		}
		User loginUser = (User) request.getSession().getAttribute(UserConstant.SESSION_USER);
		user.setCreateBy(loginUser.getUserId());
		
		String[] res = userService.updateUser(user);
		// 删除已添加的角色
		userService.deleteUserRole(user.getUserId());
		
		if(roles!=null && roles.length>0) {
			List<UserRole> userRoleList = new ArrayList<UserRole>();
			// 添加角色
			for(String roleId : roles) {
				UserRole userRole = new UserRole();
				userRole.setUserId(user.getUserId());
				userRole.setRoleId(Long.valueOf(roleId));
				userRole.setCreateBy(loginUser.getUserId());
				userRoleList.add(userRole);
			}
			
			userService.addUserRole(userRoleList);
		}
		
		if(SUCCESS.equals(res[0])) {
			result.put("success", 0);
			result.put("msg", "修改用户成功！");
			this.writeData(result);
			return;
		}else {
			result.put("success", 1);
			result.put("msg", res[1]);
			this.writeData(result);
			return;
		}
	}
	
	@RequestMapping("/showRoleList")
	public String showRoleList() {
		// 获取权限列表
		String jsontree = userService.queryMenuJsonTree(null);
		request.setAttribute("jsontree", jsontree);
				
		List<RoleBean> roleList = userService.queryRoleBeanList();
		
		request.setAttribute("roleList", roleList);
		
		return "/system/roleList";
	}
	
	@RequestMapping("/gotoAddRole")
	public String gotoAddRole() {
		// 获取权限列表
		String jsontree = userService.queryMenuJsonTree(null);
		request.setAttribute("jsontree", jsontree);
		
		return "/system/addRole";
	}
	
	@RequestMapping("/queryRoleInfo")
	@ResponseBody
	public void queryRoleInfo() {
		JSONObject result = new JSONObject();
		String roleId = this.getValue("roleId");
		
		RoleBean roleBean = userService.queryRoleBeanByRoleId(Long.valueOf(roleId));
		result.put("role", roleBean);
		
		// 获取权限列表
		String jsontree = userService.queryMenuJsonTree(Long.valueOf(roleId));
		result.put("jsontree", jsontree);
		result.put("success", 0);
		
		this.writeData(result);
	}
	
	@RequestMapping("/addRole")
	@ResponseBody
	public void addRole() {
		JSONObject result = new JSONObject();
		
		String roleName = this.getValue("roleName");
		String remark = this.getValue("remark");
		if(ValidateUtil.empty(roleName)) {
			result.put("success", 1);
			result.put("msg", "角色名称不能为空");
			this.writeData(result);
			return;
		}
		
		Role role = new Role();
		role.setRoleName(roleName);
		role.setRemark(remark);
		
		User loginUser = (User) request.getSession().getAttribute(UserConstant.SESSION_USER);
		role.setCreateBy(loginUser.getUserId());
		String[] res = userService.addRole(role);
		
		String menuIds = this.getValue("menuIds");
		System.out.println(menuIds);
		
		if(SUCCESS.equals(res[0])) {
			
			String[] menuIdArr = menuIds.split(",");
			List<RoleMenu> roleMenuList = new ArrayList<RoleMenu>();
			for(String menuIdStr : menuIdArr) {
				if(ValidateUtil.empty(menuIdStr)) {
					continue;
				}
				
				RoleMenu roleMenu = new RoleMenu();
				roleMenu.setRoleId(role.getRoleId());
				roleMenu.setMenuId(Long.valueOf(menuIdStr));
				roleMenu.setCreateBy(loginUser.getUserId());
				
				roleMenuList.add(roleMenu);
			}
			userService.addRoleMenuList(roleMenuList);
			
			result.put("success", 0);
			result.put("msg", "添加成功");
			this.writeData(result);
		}else {
			result.put("success", 1);
			result.put("msg", "角色添加失败");
			this.writeData(result);
		}
		
	}
	
	@RequestMapping("/updateRole")
	@ResponseBody
	public void updateRole() {
		JSONObject result = new JSONObject();
		
		String roleId = this.getValue("roleId");
		String roleName = this.getValue("roleName");
		String remark = this.getValue("remark");
		if(ValidateUtil.empty(roleId)) {
			result.put("success", 1);
			result.put("msg", "数据异常");
			this.writeData(result);
			return;
		}
		
		if(ValidateUtil.empty(roleName)) {
			result.put("success", 1);
			result.put("msg", "角色名称不能为空");
			this.writeData(result);
			return;
		}
		
		Role role = new Role();
		role.setRoleId(Long.valueOf(roleId));
		role.setRoleName(roleName);
		role.setRemark(remark);
		
		User loginUser = (User) request.getSession().getAttribute(UserConstant.SESSION_USER);
		role.setCreateBy(loginUser.getUserId());
		String[] res = userService.updateRole(role);
		
		String menuIds = this.getValue("menuIds");
		
		if(SUCCESS.equals(res[0])) {
			
			// 删除之前菜单权限
			userService.delRoleMenuBtRoleId(Long.valueOf(roleId));
			
			String[] menuIdArr = menuIds.split(",");
			List<RoleMenu> roleMenuList = new ArrayList<RoleMenu>();
			for(String menuIdStr : menuIdArr) {
				if(ValidateUtil.empty(menuIdStr)) {
					continue;
				}
				
				RoleMenu roleMenu = new RoleMenu();
				roleMenu.setRoleId(role.getRoleId());
				roleMenu.setMenuId(Long.valueOf(menuIdStr));
				roleMenu.setCreateBy(loginUser.getUserId());
				
				roleMenuList.add(roleMenu);
			}
			userService.addRoleMenuList(roleMenuList);
			
			result.put("success", 0);
			result.put("msg", "添加成功");
			this.writeData(result);
		}else {
			result.put("success", 1);
			result.put("msg", "角色添加失败");
			this.writeData(result);
		}
		
	}

}
